#include "doctypedelegate.h"
#include <QComboBox>

DocTypeDelegate::DocTypeDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}

QWidget *DocTypeDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
                                       const QModelIndex &index) const
{
    Q_UNUSED(option)
    Q_UNUSED(index)

    QComboBox *comboBox = new QComboBox(parent);
    //添加可选项
    comboBox->addItem("安装指南");
    comboBox->addItem("说明文档");
    comboBox->addItem("设计文档");
    comboBox->addItem("其他文档");

    return comboBox;
}

void DocTypeDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
    if (comboBox) {
        //获取文本
        QString currentText = index.data(Qt::DisplayRole).toString();
        //下拉框中进行查找该文本
        int currentIndex = comboBox->findText(currentText);
        if (currentIndex >= 0) {
            comboBox->setCurrentIndex(currentIndex);
        }
    }
}

void DocTypeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
                                   const QModelIndex &index) const
{
    QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
    if (comboBox) {
        //多态 调用我们重写的虚函数
        model->setData(index, comboBox->currentText(), Qt::EditRole);
    }
}

void DocTypeDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option,
                                           const QModelIndex &index) const
{
    Q_UNUSED(index)
    //更新我们编译器尺寸
    editor->setGeometry(option.rect);
}
